package com.sora.imeiplugin;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.telephony.TelephonyManager;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;

import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.embedding.engine.plugins.activity.ActivityAware;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugin.common.PluginRegistry;
import io.flutter.plugin.common.PluginRegistry.Registrar;

/**
 * ImeiPlugin
 */
public class ImeiPlugin implements FlutterPlugin, MethodCallHandler, ActivityAware, PluginRegistry.RequestPermissionsResultListener {

    private Activity activity;
    private ContentResolver contentResolver;

    private static final int MY_PERMISSIONS_REQUEST_READ_PHONE_STATE = 1995;
    private static final int MY_PERMISSIONS_REQUEST_READ_PHONE_STATE_IMEI_MULTI = 1997;
    private static final String PREF_UNIQUE_ID = "PREF_UNIQUE_ID_99599";
    private Result mResult;
    private boolean ssrpr = false;

    private static final String ERCODE_PERMISSIONS_DENIED = "2000";
    private AtomicBoolean re = new AtomicBoolean(false);

    @Override
    public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) {
        final MethodChannel channel = new MethodChannel(binding.getBinaryMessenger(), "sora/imei_plugin");
        ImeiPlugin plugin = new ImeiPlugin();
        channel.setMethodCallHandler(this);
    }

    @Override
    public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
    }

   private void getImei(Activity activity, Result result) {
        try {
            if (!re.get()) {
                re.set(true);
                result.success(getUUID(activity));
            }
        } catch (Exception ex) {
            if (!re.get()) {
                re.set(true);
                result.success("unknown");
            }
        }
    }

    private void getImeiMulti(Activity activity, Result result) {
        try {
            if (!re.get()) {
                re.set(true);
                result.success(Arrays.asList(getUUID(activity)));
            }
        } catch (Exception ex) {
            if (!re.get()) {
                re.set(true);
                result.success("unknown");
            }
        }
    }

    private synchronized static String getUUID(Context context) {

        SharedPreferences sharedPrefs = context.getSharedPreferences(
                PREF_UNIQUE_ID, Context.MODE_PRIVATE);
        String uniqueID = sharedPrefs.getString(PREF_UNIQUE_ID, null);
        if (uniqueID == null) {
            uniqueID = UUID.randomUUID().toString();
            SharedPreferences.Editor editor = sharedPrefs.edit();
            editor.putString(PREF_UNIQUE_ID, uniqueID);
            editor.commit();
        }

        return uniqueID;
    }

    private void getID(Context context, Result result) {
        if (!re.get()) {
            re.set(true);
            result.success(getUUID(context));
        }
    }

    @Override
    public void onMethodCall(MethodCall call, @NonNull Result result) {
        mResult = result;
        Boolean b = call.<Boolean>argument("ssrpr");
        ssrpr = b != null && b;
        switch (call.method) {
            case "init":
                break;
            case "getImei":
                getImei(activity, mResult);
                break;
            case "getImeiMulti":
                getImeiMulti(activity, result);
                break;
            case "getId":
                getID(activity, result);
                break;
            default:
                mResult.notImplemented();
                break;
        }

    }

    @Override
    public boolean onRequestPermissionsResult(int requestCode, String[] permissions, int[] results) {
        if (requestCode == MY_PERMISSIONS_REQUEST_READ_PHONE_STATE || requestCode == MY_PERMISSIONS_REQUEST_READ_PHONE_STATE_IMEI_MULTI) {
            if (results[0] == PackageManager.PERMISSION_GRANTED) {
                if (requestCode == MY_PERMISSIONS_REQUEST_READ_PHONE_STATE) {
                    getImei(activity, mResult);
                } else {
                    getImeiMulti(activity, mResult);
                }
            } else {
                if (!re.get()) {
                    re.set(true);
                    mResult.error(ERCODE_PERMISSIONS_DENIED, "Permission Denied", null);
                }
            }
            return true;
        }

        return false;
    }


    @Override
    public void onAttachedToActivity(@NonNull ActivityPluginBinding binding) {
        activity = binding.getActivity();
        contentResolver = binding.getActivity().getContentResolver();
        binding.addRequestPermissionsResultListener(this);
    }

    @Override
    public void onDetachedFromActivityForConfigChanges() {

    }

    @Override
    public void onReattachedToActivityForConfigChanges(@NonNull ActivityPluginBinding binding) {
        activity = null;
        contentResolver = null;
        binding.removeRequestPermissionsResultListener(this);
    }

    @Override
    public void onDetachedFromActivity() {

    }
}
